<script lang="ts" setup>
import { ref, reactive, type PropType, onMounted } from 'vue'
import {
  NSpace,
  NButton,
  cardProps,
  type FormInst,
  NForm,
  NFormItem,
  NInput,
  type FormRules,
  useMessage,
  NTreeSelect,
  NInputNumber,
  NRadioGroup,
  NRadioButton
} from 'naive-ui'
import ModalContent from '@/components/ModalContent'
import type { RoleModel } from '@/api/role'
import { sendRequest } from '@/utils/api'
import type { DicTreeModel } from '@/api/dic'
import type { HttpResponse } from '@/utils/http'
import { keysOf } from '@/utils/object'
import { RoleDicCode } from '@/enums/system'

const props = defineProps({
  ...cardProps,
  editId: [Number, undefined] as PropType<number | undefined>
})
const emit = defineEmits<{
  (event: 'close'): void
  (event: 'update'): void
}>()

const message = useMessage()
const formRef = ref<FormInst | null>(null)
const form = reactive<RoleModel>({
  id: props.editId,
  roleStatus: 1
} as RoleModel)
const loading = ref(false)
const roleTypeOptions = ref<DicTreeModel[] | undefined>()
const formRules: FormRules = {
  roleName: {
    required: true,
    trigger: ['blur'],
    message: '角色名称不能为空'
  },
  roleTypeId: {
    required: true,
    type: 'number',
    trigger: ['blur'],
    message: '角色类型不能为空'
  }
}

// 获取角色类型选项
const queryRoleOptions = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'dic',
      api: 'getTree',
      override: {
        params: {
          dicCode: RoleDicCode.Parent
        }
      }
    })
    if (error) throw error
    roleTypeOptions.value = res.data[0]?.children
  } catch (error: any) {
    message.error(error.message)
  }
}

const submit = () => {
  formRef.value?.validate(async (err) => {
    if (err) return
    loading.value = true
    const [error, res] = await sendRequest({
      module: 'role',
      api: props.editId ? 'update' : 'save',
      override: {
        data: form
      }
    })
    loading.value = false

    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg)
    emit('close')
    emit('update')
  })
}

onMounted(() => {
  queryRoleOptions()

  // 修改回显
  if (props.editId) {
    sendRequest<HttpResponse<RoleModel>>({
      module: 'role',
      api: 'info',
      uri: {
        id: props.editId
      }
    }).then(([err, res]) => {
      if (err) return
      keysOf(res.data).forEach((e) => {
        form[e] = res.data[e] as never
      })
    })
  }
})
</script>

<template>
  <ModalContent v-bind="$props">
    <NForm
      :model="form"
      :rules="formRules"
      ref="formRef"
      label-placement="left"
      label-width="80"
      size="small"
      style="min-width: 450px"
    >
      <NFormItem
        label="角色名称"
        path="roleName"
      >
        <NInput v-model:value="form.roleName" />
      </NFormItem>
      <NFormItem
        label="角色类型"
        path="roleTypeId"
      >
        <NTreeSelect
          v-model:value="form.roleTypeId"
          :options="roleTypeOptions"
          key-field="id"
          label-field="name"
        />
      </NFormItem>
      <NFormItem
        label="排序码"
        path="sortIndex"
      >
        <NInputNumber v-model:value="form.sortIndex" />
      </NFormItem>
      <NFormItem
        label="备注"
        path="describe"
      >
        <NInput
          v-model:value="form.describe"
          type="textarea"
        />
      </NFormItem>
      <NFormItem
        label="状态"
        path="roleStatus"
      >
        <NRadioGroup v-model:value="form.roleStatus">
          <NRadioButton
            :value="1"
            label="正常"
          />
          <NRadioButton
            :value="0"
            label="禁用"
          />
        </NRadioGroup>
      </NFormItem>
    </NForm>

    <template #action>
      <NSpace
        justify="center"
        style="padding-bottom: 20px"
      >
        <NButton @click="$emit('close')">取消</NButton>
        <NButton
          @click="submit"
          :loading="loading"
          :disabled="loading"
        >
          确定
        </NButton>
      </NSpace>
    </template>
  </ModalContent>
</template>
